package com.huangwenshuo.futurestarschoolmanagement.security;

import com.alibaba.fastjson.JSONObject;
import com.huangwenshuo.futurestarschoolmanagement.pojo.po.JwtUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component("imoocAuthenticationSuccessHandler")
public class ImoocAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
            logger.info("登录成功,用户名：{}",((JwtUser)authentication.getPrincipal()).getUsername());
        response.setContentType("application/json;charset=utf-8");
        String success = "{\n" +
                "\t\"status\": 200,\n" +
                "\t\"msg\": \"登陆成功\"\n" +
                "}";
        Map<String,Object> res = new HashMap<>();
        res.put("status",200);
        res.put("msg","登陆成功");
        Map<String,Object> data = new HashMap<>();
        data.put("token",response.getHeader("token"));
        res.put("data",data);
        success = JSONObject.toJSONString(res);
        response.getWriter().write(success);
//        redisService.set("springsecurity3","123");
//        redisService.set("springsecurity3"+":"+jwtUser.getUsername(),jwtUserString);
//        if(LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
//            response.setContentType("application/json;charset=UTF-8");
//            //把authentication对象转成json格式的字符串，
//            //然后以application/json的形式写会到响应里边去
//            response.getWriter().write(objectMapper.writeValueAsString(authentication));
//
//        }else{
//            //父类的方法就是跳转
//            super.onAuthenticationSuccess(request,response,authentication);
//
//        }

    }
}
